import { ref } from 'vue'
import { defineStore } from 'pinia'

import { loginAPI } from '@/apis/user'
import { useCartStore } from './cart'
import {mergeCartAPI} from '@/apis/cart'

export const useUserStore = defineStore('user', () => {
  const cartStore = useCartStore()
  const userInfo = ref({})

  //* 登录时获取数据 要新增合并购物车操作
  const getUserInfo = async ({ account, password }) => {
    const res = await loginAPI( account, password )
    userInfo.value = res.result
    await mergeCartAPI(cartStore.cartList.map((item) => {
      return {
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }
    }))
    cartStore.updateNewList()
  }

  //*退出时清除数据
  const clearUserInfo = () => {
    userInfo.value = {}
    cartStore.clearCart()
  }
 

  return { userInfo, getUserInfo,clearUserInfo }
},
  {
  persist: true
})
